package com.zenaprod.twodcore.ui;

import com.zenaprod.framework.log.ZLog;

import javax.swing.*;
import java.awt.*;



public class GameView  extends JPanel {
    protected Ui ui;
    protected int width, height;
    protected int fps = 60;
    protected boolean stop = false;
    protected Thread repaintThread;

    public GameView(int width, int height, int fps){
        super();
        this.width = width;
        this.height = height;
        this.fps = fps;
        this.ui = new Ui();

        Dimension size = new Dimension(width, height);
        setSize(size);
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);

        createRepaintThread();
    }


    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2D = (Graphics2D) g;
        ui.draw(g2D);
    }

    public void startRepaint() {
        ZLog.i("Start repaint");
        repaintThread.start();
    }

    public void stopRepaint() {
        ZLog.i("Stop repaint");
        stop = true;
    }

    private void createRepaintThread() {
        this.repaintThread = new Thread() {
            public void run() {
                long sleepTime = 1000 / GameView.this.fps;
                while (!stop) {
                    repaint();
                    try {
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        ZLog.e(e);
                    }
                }
            }
        };
    }


    public Ui getUi() {
        return ui;
    }
}
